<template>
  <div>
    <el-card>
      <el-row :gutter="20" class="asd">
        <el-col :span="7">
          <el-input
            v-model="queryInfo.title"
            placeholder="根据用户名搜索"
          ></el-input>
        </el-col>
        <el-col :span="7">
          <el-button @click="queryInfo.title = ''">清除</el-button>
          <el-button type="primary" @click="loadList(queryInfo)"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1">
          <el-button
            @click="addpower()"
            class="addlist"
            type="success"
            icon="el-icon-edit"
            >新增权限组件</el-button
          >
        </el-col>
      </el-row>
      <el-alert type="info"
        ><i class="el-icon-info"></i> 共{{ total }}条记录</el-alert
      >

      <el-table
        ref="multipleTable"
        :data="userlist"
        tooltip-effect="dark"
        style="width: 100%"
      >
        <el-table-column type="selection"> </el-table-column>
        <el-table-column label="用户名" prop="title"></el-table-column>
        <el-table-column sortable label="日期">
          <template slot-scope="scope">{{
            scope.row.create_date | LocalizedFormat
          }}</template>
        </el-table-column>
        <el-table-column label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              circle
              @click="exitlist(scope.row.id)"
            ></el-button>
            <el-button
              @click="delpowerLists(scope.row.id)"
              type="danger"
              plain
              icon="el-icon-delete"
              circle
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="queryInfo.pagesize"
        layout="prev, pager, next, sizes, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      @close="dialogFormVisibles"
      title="创建权限组"
      width="50%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="ruleForm"
        label-width="70px"
        ref="addformRef"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
      </el-form>
      <div class="qwe">
        <span class="qwer">权限管理</span>
        <el-tree
          :data="rightslistss"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="defKey"
          ref="treeRef"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addlists(ruleForm.name)"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      @close="dialogFormVisibles"
      title="创建权限组"
      width="50%"
      :visible.sync="exitdialogFormVisible"
    >
      <el-form
        :model="ruleForm"
        label-width="70px"
        ref="addformRef"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
      </el-form>
      <div class="qwe">
        <span class="qwer">权限管理</span>
        <el-tree
          :data="rightslistss"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="defKey"
          ref="treeRef"
        >
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exitdialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="exitslists(exitdata.id, ruleForm.name)"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, getpowerList, delpowerList, addpowerList, showpowerList, exitspowerList } from '../../api/user'

export default {
  data () {
    return {
      userlist: [],
      queryInfo: {
        page: 1,
        pagesize: 10,
        title: ''
      },
      total: 0,
      dialogFormVisible: false,
      exitdialogFormVisible: false,
      ruleForm: {
        name: ''
      },
      rightslist: [],
      rightslists: [],
      rightslistss: null,
      defaultProps: {
        children: 'childs',
        label: 'title'
      },
      addFormRules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
      },
      defKey: [],
      exitdata: {}
    }
  },
  created () {
    this.loadList(this.queryInfo)
  },

  methods: {
    // async getUserList () {
    //   const { data } = await this.$http.get('/permissions', { headers: { Authorization: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIsImlhdCI6MTYwOTMxNzYyOCwiZXhwIjoxNjQwNDIxNjI4fQ.9qV09QWo_HSKJcfNo0Wt-qtb00jntxYeiA7yAFq_weM' } }, { params: { page: 1, pagesize: 10, keyword: '' } })
    //   this.userlist = data.list
    //   this.total = data.counts
    //   console.log(data)
    // }
    async loadList (queryInfo) {
      try {
        const data = await getUserList(queryInfo)
        // console.log(data)
        if (data.status === 200) {
          this.userlist = data.data.list
          this.total = data.data.counts
          // console.log(this.userlist)
        } else {
          this.$message.error('获取失败')
        }
      } catch (err) {
        this.$message.error('错了哦.失败')
      }
    },
    handleSizeChange (newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.loadList(this.queryInfo)
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.page = newPage
      this.loadList(this.queryInfo)
    },
    async addpower () {
      this.dialogFormVisible = true
      try {
        const data = await getpowerList()
        this.rightslist = data.data
        // console.log(this.rightslist)
        this.rightslist.forEach(item => {
          // console.log(item)
          const json = JSON.parse(JSON.stringify(item).replace(/points/g, 'childs'))
          // console.log(json)
          this.rightslists.push(json)
        })
        // console.log(this.rightslists)
        var arr = [{
          title: '系统菜单和页面权限点',
          id: '',
          childs: this.rightslists
        }]
        // console.log(arr)
        this.rightslistss = arr
        // console.log(this.rightslistss)
      } catch (err) {
        this.$message.error('错了哦.失败')
      }
    },
    async delpowerLists (id) {
      const deluserlilst = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(deluserlilst)
      if (deluserlilst !== 'confirm') {
        return this.$message.info('删除取消!')
      }
      // console.log(id)
      await delpowerList(id)
      this.loadList(this.queryInfo)
    },
    dialogFormVisibles () {
      this.rightslists = []
      this.defKey = []
      this.dialogFormVisible = false
      this.$refs.addformRef.resetFields()
    },
    async addlists (name) {
      const idStr = [
        ...this.$refs.treeRef.getCheckedKeys()
        // ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      if (idStr[0] === '') {
        idStr.splice(0, 1)
      }
      // console.log(idStr)
      if (name === '') {
        return this.$message.info('请输入用户名!')
      }
      try {
        await addpowerList({
          title: name,
          permissions: idStr
        })
      } catch (err) {
        return this.$message.info('权限不能为空!')
      }
      this.loadList(this.queryInfo)
      this.dialogFormVisible = false
    },
    async exitlist (id) {
      // this.exitdialogFormVisible = true
      this.exitdialogFormVisible = true
      try {
        const data = await getpowerList()
        this.rightslist = data.data
        // console.log(this.rightslist)
        this.rightslist.forEach(item => {
          // console.log(item)
          const json = JSON.parse(JSON.stringify(item).replace(/points/g, 'childs'))
          // console.log(json)
          this.rightslists.push(json)
        })
        // console.log(this.rightslists)
        var arr = [{
          title: '系统菜单和页面权限点',
          id: '',
          childs: this.rightslists
        }]
        // console.log(arr)
        this.rightslistss = arr
        // console.log(this.rightslistss)
      } catch (err) {
        this.$message.error('错了哦.失败')
      }
      const data = await showpowerList(id)
      console.log(data)
      this.defKey = data.data.permissions
      this.ruleForm.name = data.data.title
      this.exitdata = data.data
      console.log(this.exitdata)
    },
    async exitslists (id, name) {
      const idStr = [
        ...this.$refs.treeRef.getCheckedKeys()
        // ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // idStr = ['',20,30]
      if (id === '') {
        idStr.splice(0, 1)
      }
      // console.log(idStr)
      if (name === '') {
        return this.$message.info('请输入用户名!')
      }
      if (idStr === []) {
        return this.$message.info('权限不能为空!')
      }
      var data = {
        id: id,
        title: name,
        permissions: idStr
      }
      try {
        await exitspowerList(id, data)
      } catch (err) {
        return this.$message.info('请重试!')
      }
      this.loadList(this.queryInfo)
      this.exitdialogFormVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-top: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
/deep/ .el-dialog__header {
  background: #409eff;
}
/deep/ .el-dialog {
  overflow: hidden;
  border-radius: 9px 9px;
}
.el-input__inner {
  width: 150px;
}
.el-form {
  display: flex;
  align-items: center;
  justify-content: center;
}
.el-tree {
  display: flex;
  align-items: center;
  justify-content: center;
}
.qwe {
  position: relative;
}
.qwer {
  position: absolute;
  z-index: 999;
  right: 65%;
}
.asd {
  position: relative;
}
.addlist {
  position: absolute;
  right: 10px;
}
</style>
